const Router = require('koa-router')
const router = new Router()
const Users = require('../models/Users')
const { NotFoundError } = require('../utils/customError')
const auth = require('../middlewares/auth')
const createToken = require('../config/createToken')
const { loginUserInfo, frontUserInfo } = require('../attributes/users')
const { getCurrentDate } = require('../utils/Date')
const redis = require('../config/redis')

router.prefix('/user')
// 后台管理员登录
router.post('/login', async (ctx) => {
  const data = ctx.request.body
  // const cookieCaptcha = ctx.cookies.get('captcha');
  const cookieCaptcha = await redis.get(`captcha:${data['captcha'].toLowerCase()}`)
  console.log('captcha', cookieCaptcha)
  if (!data['captcha']) {
    ctx.body = {
      code: 400,
      data: '验证码不能为空',
    }
    return
  }
  if (data.captcha.toLowerCase() !== cookieCaptcha.toLowerCase()) {
    ctx.body = {
      code: 400,
      data: '验证码错误',
    }
    return
  }
  if (!data.username || !data.password) {
    throw new NotFoundError('用户名或密码不能为空')
  }
  const user = await Users.findOne({
    where: {
      username: data.username,
      password: data.password,
    },
    attributes: loginUserInfo,
  })
  if (!user) {
    ctx.body = {
      code: 400,
      data: '用户名或密码错误',
    }
    return
  }
  const date = getCurrentDate()
  // 更新数据库登录时间
  await Users.update(
    {
      lastLogin: date,
    },
    {
      where: { id: user.id },
    },
  )
  const token = createToken({
    id: user.id,
    username: user.username,
    lastLogin: date,
    avatar: user.avatar,
    role: user.role,
  })
  // 存入 Redis（用于分布式校验）1天
  await redis.set(`token:${user.username}`, token, 'EX', 60 * 60 * 24)
  // 清除验证码
  await redis.del(`captcha:${data['captcha']}`)
  ctx.body = {
    code: 200,
    data: { user },
  }
})
// const tokenBlacklist = new Set();
// // 登出接口
// router['post']('/logout', auth, async (ctx) => {
//    const token = ctx.headers.authorization.split(' ')[1];
//    tokenBlacklist.add(token);
//    ctx.body = {
//       code: 200,
//       data: "登出成功"
//    }
// });
router.get('/info', auth, async (ctx) => {
  if (!ctx.state.user) {
    throw new NotFoundError('用户当前未登录')
  }
  const u = JSON.parse(JSON.stringify(ctx.state.user))
  const user = await Users.findOne({
    where: {
      id: u.id,
    },
  })
  ctx.body = {
    code: 200,
    data: user,
  }
})

// 用户端获取博主信息
router['get']('/getBloggerInfo', async (ctx) => {
  const user = await Users.findOne({
    where: {
      isBanned: 'N',
      id: 1,
    },
    attributes: frontUserInfo,
  })
  if (!user) {
    throw new NotFoundError('博主信息不存在')
  }
  ctx.body = {
    code: 200,
    data: user,
  }
})
// 保存个人信息
router.post('/save', auth, async (ctx) => {
  const data = ctx.request.body
  if (!data.id) {
    return (ctx.body = {
      code: 400,
      data: {
        message: '用户id不能为空',
      },
    })
  }
  try {
    await Users.update(data, {
      where: {
        id: data.id,
      },
    })
    return (ctx.body = {
      code: 200,
      data: true,
    })
  } catch (e) {
    return (ctx.body = {
      code: 500,
      data: {
        message: e.message,
      },
    })
  }
})
// 修改密码
router.post('/changePassword', auth, async (ctx) => {
  const { id, currentPassword, newPassword } = ctx.request.body
  if (!id || !currentPassword || !newPassword) {
    return (ctx.body = {
      code: 400,
      data: {
        message: '参数不能为空',
      },
    })
  }
  try {
    const user = await Users.findOne({
      where: { id },
    })
    if (user.password !== currentPassword) {
      return (ctx.body = {
        code: 400,
        data: {
          message: '旧密码错误',
        },
      })
    }
    await Users.update(
      {
        password: newPassword,
      },
      {
        where: { id },
      },
    )
    return (ctx.body = {
      code: 200,
      data: true,
    })
  } catch (e) {
    return (ctx.body = {
      code: 500,
      data: {
        message: e.message,
      },
    })
  }
})
module.exports = router
